﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SubSonic.Query;
using SubSonic.Schema;

namespace DataAccess.DbHelper {

	public class UpdateHelper {
		//定义数据源，即更新那个数据库的链接源，多个数据库时可以直接修改数据源来对不同数据库进行更新操作
		SubSonic.DataProviders.IDataProvider provider = null;

		 #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
		public UpdateHelper() { 
            //获取数据源
            provider = SubSonic.DataProviders.ProviderFactory.GetProvider();
        }

        #endregion

		/// <summary>
		/// 泛型式修改——有条件
		/// </summary>
		/// <typeparam name="T">泛型集合对象</typeparam>
		/// <param name="setValue">要更新的字段与值</param>
		/// <param name="wheres">修改条件</param>
        //public int Update<T>(Dictionary<string, object> setValue, List<ConditionHelper.SqlqueryCondition> wheres = null) where T : IActiveRecord, new() {
		public int Update<T>(Dictionary<string, object> setValue, List<ConditionHelper.SqlqueryCondition> wheres) where T : IActiveRecord, new() {
			try {
				var qry = new Update<T>(provider);

				//添加值
				foreach (KeyValuePair<string, object> keyValue in setValue) {
					qry.Set(keyValue.Key).EqualTo(keyValue.Value);
				}

				//添加条件
				if (wheres != null)
					qry.Constraints = ConditionHelper.SqlqueryCondition.Condition(wheres);

				var cmd = qry.GetCommand();

				return provider.ExecuteQuery(cmd);
			}
			catch (Exception) {
				return 0;
				//throw new Exception("修改数据异常,执行语句" + Exsql, e);
			}
		}

	}
}
